<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
use think\Request;
use think\View;
use think\Db;
use app\index\validate\Valid;

class Netbasicsales extends Common
{
    //新的保存
    public function newadd(){
         $request = Request::instance();


        $data = $request->post();
       
       $jxs=$data["jxs_id"];
       if(!$jxs){
         echo  json_encode([
                                "success"=>false,
                                "msg"=>"经销商必须选择"
                            ]);die;
       }
      $net=$data["net_id"];
       if(!$net){
         echo  json_encode([
                                "success"=>false,
                                "msg"=>"网点必须选择"
                            ]);die;
       }
       
       $pros=$data["pro"];
       $adddata=[];
       for($i=0;$i<count($pros["pro_id"]);$i++){
            $pid=$pros["pro_id"][$i];
            $parr=Db::table("pro_products")->where(["id"=>$pid])->find();
            if(!$parr){
                echo  json_encode([
                                "success"=>false,
                                "msg"=>"存在异常的产品"
                            ]);die;
            }
           
            $flag=0;
            for($j=1;$j<=12;$j++){
                if($pros[$j][$i]){
                    $flag=1;
                    $tmp["cuser"]=Session::get("employee_id");$tmp["ctime"]=time();
                    $tmp["puser"]=Session::get("employee_id");$tmp["ptime"]=time();
                    $tmp["sn"]=$parr["pro_no"]; $tmp["pro_id"]=$pid;$tmp["name"]=$parr["pro_name"];
                    $tmp["jxs_id"]= $jxs;$tmp["net_id"]= $net;$tmp["unit"]= $parr["unit"];
                    $tmp["num"]=$pros[$j][$i];//$tmp["sum"]=$pros["sum"][$i];$tmp["avg"]=$pros["avg"][$i];
                    $tmp["kaoheqi2"]=$j;
                    $adddata[]=$tmp;
                }
               
            }
            if($flag==0){
                 echo  json_encode([
                                "success"=>false,
                                "msg"=>"产品{$parr["pro_name"]}至少应当有一个月的销量不为空或0"
                            ]);die;
            }
       }
       //print_r($adddata[1]);exit;
       if(!$adddata){
        echo  json_encode([
                                "success"=>false,
                                "msg"=>"至少应当存在一个以上的产品"
                            ]);die;
       }
       Db::startTrans();
       try{
            Db::table("cg_net_basic")->where("net_id=$net")->delete();
            $res1=Db::table("cg_net_basic")->insertAll($adddata);
       }catch(\Exception $e){
            Db::rollBack();
            echo  json_encode([
                                "success"=>false,
                                "msg"=>"系统繁忙请稍后再试"
                            ]);die;
       }
       if($res1){
            Db::commit();
             echo  json_encode([
                    "success"=>true,
                    "msg"=>"保存成功"
                ]);die;
       }else{
         Db::rollBack();
            echo  json_encode([
                                "success"=>false,
                                "msg"=>"系统繁忙请稍后再试"
                            ]);die;
       }
    }

	//列表
    public function index()
    {

        $sku_title = $this->request->get('sku_title');
        $title = $this->request->get('title');
        $kaoheqi_sn = $this->request->get('kaoheqi_sn');

        $this->assign(array('sku_title'=>$sku_title));
        $this->assign(array('title'=>$title));
        $this->assign(array('kaoheqi_sn'=>$kaoheqi_sn));
        $where = [];

        if($sku_title){
            $where['pro_id'] = ['exp','in(select t.id from pro_products t join pro_sku t2 on t2.id=t.sku_id where t2.sku_name like \'%'.$title.'%\')'];
        }
        if($title){
            $where['net_id'] = ['exp','in(select id from cg_net where title like \'%'.$title.'%\')'];
        }
        if($kaoheqi_sn){
            $where['kaoheqi2'] =$kaoheqi_sn ;
        }
//        if($stuff){
//            //根据模糊查询规则把admin对应的id全部查询出来
//            $ids = Db::query("select id from employee where em_name like '%{$stuff}%'");
//            $str = [];
//            foreach($ids as $k=>$v){
//                if($k==0)
//                    $str[] = " like '%\"$v[id]\"%' ";
//                else
//                    $str[] = " stuff like '%\"$v[id]\"%' ";
//            }
//            $str = implode('or',$str);
//
//            $where['stuff'] = array('exp',$str);
//        }

        $count = Db::table('cg_net_basic')->where($where)->count();
        $data = Db::table('cg_net_basic')->order("net_id desc,pro_id,kaoheqi2")->where($where)->paginate(10,$count);
//        echo Db::table('cg_system')->getLastSql();
        $page = $data->render();
        $data = $data->items();
          $maxpage=ceil($count/10);
        foreach($data as $k=>$v){
            $data[$k]['cusername'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $data[$k]['pusername'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');
            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
            $data[$k]['net_sn'] = Db::table('cg_net')->where(array('id'=>$v['net_id']))->value('sn');
            $data[$k]['net_title'] = Db::table('cg_net')->where(array('id'=>$v['net_id']))->value('title');
            $data[$k]['sell_standard'] = Db::table('pro_price')->where(array('id'=>$v['pro_id']))->value('sell_standard');
            $data[$k]['kaoheqi2'] = $v['kaoheqi2']."月";
            $data[$k]['sku_no'] = Db::table('pro_sku t')->join('pro_products t2','t2.sku_id=t.id')->where(array('t2.id'=>$v['pro_id']))->value('t.sku_no');
            $data[$k]['sku_name'] = Db::table('pro_sku t')->join('pro_products t2','t2.sku_id=t.id')->where(array('t2.id'=>$v['pro_id']))->value('t.sku_name');
        }

        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('maxpage',$maxpage);
        $this->assign('count',$count);
        return $this->fetch();
    }

    public function add(){
        //按照当前日期查找当前财年
        $currTime = time();
        $cainian = Db::table('cg_cainian')
            ->where([
                'starttime'=>['<',$currTime],
                'endtime'=>['>',$currTime]
            ])->value('id');

        //查找所有二级考核期
          $kaoheqi2s=[];
            for($i=1;$i<=12;$i++){
                $kaoheqi2s[]=["id"=>$i,"title"=>"{$i}月"];
            }   



        if($_POST){

            $validate = new Valid([
                'jxs_id|经销商'  => 'require',
                'net_id|网点'  => 'require',
            ]);
            $data = [];
            $data['jxs_id'] = $this->request->post('jxs_id');
            $data['net_id'] = $this->request->post('net_id');

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            //验证是否选择产品
            $pro = $this->request->post('pro/a');
            $old = $this->request->post('old/a');
            if((!$pro||count($pro['name'])<1)&&(!$old||count($old['name'])<1)){
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"请选择产品"
                ]);die;
            }

            //循环验证每个输入框是否为空
            if($pro){
                foreach($pro['name'] as $k=>$v){
                    if($v==''){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"第".($k+1)."个产品名称不能为空"
                        ]);die;
                    }
                    foreach($kaoheqi2s as $k1=>$v1){
                        if($pro[$v1['id']][$k]==''){
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$v1['title']."的数据不能为空"
                            ]);die;
                        }
                    }
                }
            }

            if($old){
                foreach($old['name'] as $k=>$v){
                    if($v==''){
                        echo  json_encode([
                            "success"=>false,
                            "msg"=>"第".($k+1)."个产品名称不能为空"
                        ]);die;
                    }

                    foreach($kaoheqi2s as $k1=>$v1){

                        if(isset($old[$v1['id']][$k])&&$old[$v1['id']][$k]==''){
                            echo  json_encode([
                                "success"=>false,
                                "msg"=>$v1['title']."的数据不能为空"
                            ]);die;
                        }
                    }
                }
            }

            $bool = true;
            if($pro){
                //组成插入所需要的数组
                $insert = [];
                foreach($pro['pro_id'] as $k=>$v){

                    //循环2级考核期
                    foreach($kaoheqi2s as $k1=>$v1){
                        $insert[] = [
                            'pro_id'=>$v,
                            'name'=>$pro['name'][$k],
                            'sn'=>$pro['sn'][$k],
                            'jxs_id'=>$data['jxs_id'],
                            'net_id'=>$data['net_id'],
                            'num'=>$pro[$v1['id']][$k],
                            'kaoheqi2'=>$v1['id'],
                            'avg'=>$pro['avg'][$k],
                            'sum'=>$pro['sum'][$k],
                            'cuser' => $_SESSION['think']['employee_id'],
                            'ctime' => time(),
                            'puser' => $_SESSION['think']['employee_id'],
                            'ptime' => time(),
                            'unit' => $pro['unit'][$k],
                        ];
                    }

                }
                //            dump($insert);

                $t = Db::table('cg_net_basic')->insertAll($insert);
                //echo Db::table('cg_net_basic')->getLastSql();
                if(false ===$t)
                    $bool = $t;

            }

            //修改
            if($old){
                foreach($old['pro_id'] as $k=>$v){
                    if($old['id']){
                        //循环2级考核期
                        foreach($kaoheqi2s as $k1=>$v1){

                            if(isset($old['id'][$k])&&isset($old[$v1['id']][$k])){
                                $t = Db::table('cg_net_basic')->where('id',$old['id'][$k])->update([
                                    'pro_id'=>$v,
                                    'name'=>$old['name'][$k],
                                    'sn'=>$old['sn'][$k],
                                    'jxs_id'=>$data['jxs_id'],
                                    'net_id'=>$data['net_id'],
                                    'num'=>$old[$v1['id']][$k],
                                    'kaoheqi2'=>$v1['id'],
                                    'avg'=>$old['avg'][$k],
                                    'sum'=>$old['sum'][$k],
                                    'puser' => $_SESSION['think']['employee_id'],
                                    'ptime' => time(),
                                    'unit' => $old['unit'][$k],
                                ]);
                                if(false ===$t)
                                    $bool = $t;
                            }

                        }


                    }
                }
            }

            if(false !== $bool){
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"保存成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"保存失败"
                ]);die;
            }
        }



        $this->assign('kaoheqi2s',$kaoheqi2s);

        return $this->fetch('form');
    }

    /**
     * 修改
     * @return mixed
     * @throws \think\Exception
     */
    public function update(){
        $id = $this->request->param('id');

        if($_POST){
            $validate = new Valid([
                'sn'  => 'require|unique:cg_system_group',
                'title'  => 'require|unique:cg_system_group',
            ]);
            $data = [];
            $data['id'] = $id;
            $data['sn'] = $this->request->post('sn');
            $data['title'] = $this->request->post('title');
            $data['brief'] = $this->request->post('brief');

            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            $data['cuser'] = $_SESSION['think']['employee_id'];
            $data['ctime'] = time();
            $data['puser'] = $_SESSION['think']['employee_id'];
            $data['ptime'] = time();
            $bool = Db::table('cg_system_group')->where('id',$id)->update($data);
            if(false !== $bool){
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"修改成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"修改失败"
                ]);die;
            }
            die;
        }

        $data = Db::table('cg_system_group')->where('id',$id)->find();


        $this->assign('data',$data);
        $this->assign('id',$id);

        return $this->fetch('form');
    }

    /**
     * 维护系统
     * @return mixed
     * @throws \think\Exception
     */
    public function whSystem(){
        $id = $this->request->param('id');

        $data = Db::table('cg_system_group')->where('id',$id)->find();

        //查询没分组的系统
        $meifenzu = Db::table('cg_system')->field('id,title')->where('groupid',0)->select();
        $yifenzu = Db::table('cg_system')->field('id,title')->where('groupid','<>',0)->select();


        $this->assign('data',$data);
        $this->assign('meifenzu',$meifenzu);
        $this->assign('yifenzu',$yifenzu);
        $this->assign('id',$id);

        return $this->fetch();
    }

    //    批量设置分组
    public function batchSet(){
        $id = $this->request->post('id');
        $pid = $this->request->post('pid');
        if(!$id||!$pid){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['groupid'] = $pid;
        $bool = Db::table('cg_system')->where('id','in',$id)->update($data);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设置成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设置失败"
            ]);die;
        }
    }

    //    批量取消设置分组
    public function batchSet2(){
        $id = $this->request->post('id');
        $pid = $this->request->post('pid');
        if(!$id||!$pid){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $data = [];
        $data['groupid'] = 0;
        $bool = Db::table('cg_system')->where('id','in',$id)->update($data);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"设置成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"设置失败"
            ]);die;
        }
    }


    /**
     * 删除
     * @throws \think\Exception
     */
    public function delete(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_system_group')->where(array('id'=>$id))->update(['isdel'=>1]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }


    /**
     * 启用
     * @throws \think\Exception
     */
    public function qiyong(){
        $id = $this->request->param('id');
        if(!$id){
            echo  json_encode([
                "success"=>false,
                "msg"=>"参数错误"
            ]);die;
        }
        $bool = Db::table('cg_system_group')->where(array('id'=>$id))->update(['isdel'=>0]);
        if(false !== $bool){
            echo  json_encode([
                "success"=>true,
                "msg"=>"删除成功"
            ]);die;
        }else{
            echo  json_encode([
                "success"=>false,
                "msg"=>"删除失败"
            ]);die;
        }
    }

    /**
     * 替换
     * @return mixed
     */
    public function tihuan(){
        $id = $this->request->param('id');
        if($_POST){;
            $new1 = $this->request->post('new1');
            $bool = Db::table('cg_system')->where('jxs',$id)->update(array('jxs'=>$new1));

            if(false!==$bool){
                $bool = Db::table('cg_system_jxs')->where(['jxs_id'=>$id,'system_id'=>$id])->update(array('jxs'=>$new1));

                echo  json_encode([
                    "success"=>true,
                    "msg"=>"替换成功"
                ]);
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"替换失败"
                ]);
            }
            die;
        }


        $this->assign('id',$id);
        $sn = Db::table('cg_jxs')->where('id',$id)->value('sn');
        $this->assign('sn',$sn);
        $title = Db::table('cg_jxs')->where('id',$id)->value('title');
        $this->assign('title',$title);
        $yiyou = Db::table('cg_system')->where('jxs',$id)->select();
        $this->assign('yiyou',$yiyou);

        return $this->fetch();
    }

    /**
     * 追加
     * @return mixed
     */
    public function zhuijia(){
        return $this->fetch();
    }

    //选择经销商
    public function selectJXS(){
        $this->assign('id',1);
        return $this->fetch();
    }
    //选择网点
    public function selectNet(){
        return $this->fetch();
    }
    //选择产品
    public function selectProduct(){
        return $this->fetch();
    }
    //返回分区经销商树数据
    public function zonetreeajax(){
        $data = Db::table('cg_market_zoning')->where('isdel',0)->field('id,title')->select();//查分区
        $data2 = [];
        foreach($data as $k=>$v){
            $temp = [];
            $temp['name'] = $v['title'];
            //查询省份
            $t = Db::table('cg_market_provice')->where(array('zoning'=>$v['id']))->field('id,title')->select();//查省份
            $data3 = [];
            foreach($t as $kk=>$vv){
                $temp2['name'] = $vv['title'];
                //查城市
                $tt = Db::table('cg_market_city')->where(array('provice'=>$vv['id']))->field('id,title')->select();//查城市
                $data4 = [];
                foreach($tt as $k3=>$v3){
                    $temp3['name'] = $v3['title'];
                    //查城市
                    $t3 = Db::table('cg_jxs')->where(array('city'=>$v3['id']))->field('id,title name')->select();//查经销商
                    $temp3['children'] = $t3;
                    $temp3["chkDisabled"]=true;
                    $temp3["nocheck"]=true;
                    $data4[] = $temp3;
                }
                $temp2['children'] = $data4;
                $temp2["chkDisabled"]=true;
                $temp2["nocheck"]=true;
                $data3[] = $temp2;
            }
            $temp['children'] = $data3;
            $temp["chkDisabled"]=true;
            $temp["nocheck"]=true;
            $data2[] = $temp;
        }
        echo json_encode($data2);
    }

    /**
     * 查询经销商的部分信息
     */
    public function findJxs(){
        $id = $this->request->post('id');
        $data = Db::table('cg_jxs')->where('id',$id)->field('sn,zoning,provice,city')->find();
        $data['city'] = Db::table('cg_market_city t')->join('employee t2','t2.id= t.head')->where('t.id',$data['city'])->value('t2.em_name');
        $data['provice'] = Db::table('cg_market_provice t')->join('employee t2','t2.id= t.head')->where('t.id',$data['provice'])->value('t2.em_name');
        $data['zoning'] = Db::table('cg_market_zoning t')->join('employee t2','t2.id= t.head')->where('t.id',$data['zoning'])->value('t2.em_name');
        echo json_encode($data);die;
    }

    /**
     * 返回经销桑json数据
     */
    public function provicejson(){
        //查询所有省份
        $data = Db::table('pro_products')->field('pro_name title,id')->select();

        echo json_encode(['message'=>'ok','value'=>$data,'code'=>'200','redirect'=>'']);
    }


    /**
     * 替换经销商
     * @return mixed
     * @throws \think\Exception
     */
    public function repDealer(){
        if($_POST){
            $data = [];
            $data['zoning'] = $this->request->post('zoning');
            $data['provice'] = $this->request->post('provice');
            $data['city'] = $this->request->post('city');
            $data['jxs'] = $this->request->post('jxs');
            $id = $this->request->param('id');

            $validate = new Valid([
                'zoning'  => 'require',
                'provice'  => 'require',
                'city'  => 'require',
                'jxs'  => 'require',
            ]);


            if (!$validate->check($data)) {
                echo  json_encode([
                    "success"=>false,
                    "msg"=>$validate->getError()
                ]);die;
            }

            $old = Db::table('cg_system')->where('id',$id)->value('jxs');
            $bool = Db::table('cg_system')->where('id',$id)->update($data);
            if(false !== $bool){
                Db::table('cg_system_jxs')->where(['system_id'=>$id,'jxs_id'=>$old,'default'=>1])->update(['jxs_id'=>$data['jxs']]);
                echo  json_encode([
                    "success"=>true,
                    "msg"=>"替换成功"
                ]);die;
            }else{
                echo  json_encode([
                    "success"=>false,
                    "msg"=>"替换失败"
                ]);die;
            }
        }
        $zoning = model('Zoning')->select();
        $this->assign('zoning',$zoning);
        return $this->fetch();
    }

    /**
     * 回收站
     * @return mixed
     */
    public function isdel()
    {

        $sn = $this->request->get('sn');
        $title = $this->request->get('title');
        $system_title = $this->request->get('systemName');

        $this->assign(array('sn'=>$sn));
        $this->assign(array('title'=>$title));
        $this->assign(array('systemName'=>$system_title));
        $where = [];
        $where['isdel'] = 1;
        if($sn){
            $where['sn'] = $sn;
        }
        if($title){
            $where['title'] = ['like','%'.$title.'%'];
        }
        if($system_title){
            $where['id'] = ['exp','in(select groupid from cg_system where title like \'%'.$system_title.'%\')'];
        }
//        if($stuff){
//            //根据模糊查询规则把admin对应的id全部查询出来
//            $ids = Db::query("select id from employee where em_name like '%{$stuff}%'");
//            $str = [];
//            foreach($ids as $k=>$v){
//                if($k==0)
//                    $str[] = " like '%\"$v[id]\"%' ";
//                else
//                    $str[] = " stuff like '%\"$v[id]\"%' ";
//            }
//            $str = implode('or',$str);
//
//            $where['stuff'] = array('exp',$str);
//        }

        $count = Db::table('cg_system_group')->where($where)->count();
        $data = Db::table('cg_system_group')->order("id desc")->where($where)->paginate(10,$count);
//        echo Db::table('cg_system')->getLastSql();
        $page = $data->render();
        $data = $data->items();
        foreach($data as $k=>$v){
            $data[$k]['cusername'] = Db::table('users')->where(array('id'=>$v['cuser']))->value('login_name');
            $data[$k]['pusername'] = Db::table('users')->where(array('id'=>$v['puser']))->value('login_name');
            $data[$k]['ctime'] = date('Y-m-d H:i',$v['ctime']);
            $data[$k]['ptime'] = date('Y-m-d H:i',$v['ptime']);
        }

        $this->assign('data',$data);
        $this->assign('page',$page);
        return $this->fetch();
    }


    //维护分组货号
    public function whproductAR(){
        $id = $this->request->param('id');
        $data = Db::table('cg_system_group')->where('id',$id)->find();
        $data['xitongshu'] = Db::table('cg_system')->where('groupid',$id)->count();
        $data['danpinshu'] = Db::table('cg_system_group_product')->where('groupid',$id)->count();
        $this->assign('data',$data);

        //查询分组下的产品列表
        $list = Db::table('cg_system_group_product t')->join('pro_products t2','t2.id=t.pro_id')->field('t.*,t2.pro_no,t2.pro_name')->where(['groupid'=>$id])->select();
        $this->assign('list',$list);
        return $this->fetch();
    }

    //增加产品
    public function addProduct(){
        $id = $this->request->post('id');
        $groupid = $this->request->post('groupid');

        //查询是否已存在
        $count = Db::table('cg_system_group_product')->where(['pro_id'=>$id,'groupid'=>$groupid])->count();
        if($count<=0){
            $bool = Db::table('cg_system_group_product')->insert(['pro_id'=>$id,'groupid'=>$groupid]);
            if(false !== $bool) {
                echo json_encode(['success' => true, 'msg' => 'ok']);
            }else{
                echo json_encode(['success' => false,'msg'=>'添加失败']);
            }
        }else{
            echo json_encode(['success' => false,'msg'=>'该产品已存在']);
        }

    }

    //删除产品
    public function delProduct(){
        $ids = $this->request->post('ids');

        //查询是否已存在
        if($ids!=''){
            $bool = Db::table('cg_system_group_product')->where('id','in',$ids)->delete();
            if(false !== $bool) {
                echo json_encode(['success' => true, 'msg' => 'ok']);
            }else{
                echo json_encode(['success' => false,'msg'=>'删除失败']);
            }
        }else{
            echo json_encode(['success' => false,'msg'=>'参数错误']);
        }

    }

    //批量删除系统分组到回收站
    public function batchDelete(){
        $ids = $this->request->post('ids');

        //查询是否已存在
        if($ids!=''){
            $bool = Db::table('cg_system_group')->where('id','in',$ids)->update(['isdel'=>1]);
            if(false !== $bool) {
                echo json_encode(['success' => true, 'msg' => 'ok']);
            }else{
                echo json_encode(['success' => false,'msg'=>'删除失败']);
            }
        }else{
            echo json_encode(['success' => false,'msg'=>'参数错误']);
        }

    }

    //保存货号
    public function savesn(){

        $ids = $this->request->post('sn/a');

        //查询是否已存在
        if($ids!=''){
            foreach($ids as $k=>$v){
                Db::table('cg_system_group_product')->where('id',$k)->update(['sn'=>$v]);
            }
            $bool = Db::table('cg_system_group_product')->where('id','in',$ids)->delete();
            echo json_encode(['success' => true, 'msg' => 'ok']);
        }else{
            echo json_encode(['success' => false,'msg'=>'参数错误']);
        }

    }
    //按照网点查找产品情况
    public function get_net_pros(){
         $id = $this->request->param('id');
         $pros=Db::table('cg_net_basic')->alias("b")
         ->join("pro_products p","b.pro_id=p.id")
         ->where(["b.net_id"=>$id])->group("b.pro_id")->field("p.id,p.pro_name,p.pro_no,p.unit")->select();

         $res[0]=$pros;
         $data = Db::table('cg_net_basic')->alias("b")
         ->join("pro_products p","b.pro_id=p.id")
         ->where(["b.net_id"=>$id])
         ->field("p.id as pid,b.kaoheqi2,b.num,b.sum,b.avg")->select();
            $kaoheqi2s=[];
            for($i=1;$i<=12;$i++){
                $kaoheqi2s[]=["id"=>$i,"title"=>"{$i}月"];
            }  

        $protrs=[]; 
        for($i=0;$i<count($pros);$i++){
            $str="<tr id='id{$pros[$i]["id"]}'> <td style='width:9.2%;'><input name='pro[pro_id][]' value='{$pros[$i]['id']}' type='hidden'>";
            $str.="<input  value='{$pros[$i]["pro_name"]}' type='text' style='max-width:100px;' class='form-control'></td>";
            $str.="<td style='width:9.2%;'>{$pros[$i]["pro_no"]}</td>";
            $sum=0;$avgc=0;
            for($j=0;$j<count($kaoheqi2s);$j++){
                $flag=0;
                for($k=0;$k<count($data);$k++){
                    if($data[$k]["pid"]==$pros[$i]["id"]&&$kaoheqi2s[$j]["id"]==$data[$k]["kaoheqi2"]){
                         $str .= "<td style=\"width:5.633%;\"><input name=\"pro[".$kaoheqi2s[$j]["id"]."][]\" type=\"number\" class=\"form-control aa\" value=\"{$data[$k]["num"]}\">{$pros[$i]['unit']}</td>";
                         $sum+=$data[$k]["num"];$avgc+=1;
                         $flag=1;
                    }
                }
                if($flag==0){
                      $str .= "<td style=\"width:5.633%;\"><input name=\"pro[".$kaoheqi2s[$j]["id"]."][]\" type=\"number\" class=\"form-control aa\" value=\"\">{$pros[$i]['unit']}</td>";
                }

            }
            $avg=round($sum/$avgc,2);
            $str.="<td style='width:7.0%;' ><input name='pro[sum][]' type='number' class='form-control sum' readonly value='{$sum}'></td>";
            $str.="<td style='width:7.0%;' ><input name='pro[avg][]' type='number' class='form-control avg' readonly value='{$avg}'></td></tr>";
            $protrs[]=$str;
        }

        $res[1]=$protrs;
        return json_encode($res);
    }

    //按照id查找产品信息
    public function search_product_by_id(){
        $id = $this->request->param('id');
        $jxs_id = $this->request->param('jxs_id');
        $net_id = $this->request->param('net_id');



            $kaoheqi2s=[];
            for($i=1;$i<=12;$i++){
                $kaoheqi2s[]=["id"=>$i,"title"=>"{$i}月"];
            }   


        //判断该产品在所选的经销商和网点是否已经存在
        $cnt = Db::table('cg_net_basic')
            ->where([
                'jxs_id'=>$jxs_id,
                'net_id'=>$net_id,
                'pro_id'=>$id
            ])
            ->count();

        if($cnt>0){
            $data = Db::table('cg_net_basic')
                ->where([
                    'jxs_id'=>$jxs_id,
                    'net_id'=>$net_id,
                    'pro_id'=>$id
                ])
                ->select();
                $proarr= Db::table('pro_products')->where('id',$id)->find();

            $str = '';
            $sum=0;$avgc=0;
            foreach($kaoheqi2s as $k=>$v){
                $flag=0;
                  
                foreach($data as $key=>$value){
                    if($v['id']==$value['kaoheqi2']){
                        $flag=1;
                        $str .= "<td style=\"width:5.633%;\"><input name=\"pro[".$v['id']."][]\" type=\"number\" class=\"form-control aa\" value=\"{$value["num"]}\">{$proarr['unit']}</td>";
                         $sum+=$value["num"];$avgc+=1;
                    }
                }
                if($flag==0){
                     $str .= "<td style=\"width:5.633%;\"><input name=\"pro[".$v['id']."][]\" type=\"number\" class=\"form-control aa\" value=\"\">{$proarr['unit']}</td>";
                }
            }

            $avg=round($sum/$avgc,2);
            $aaa = <<<EOF
<tr id="id{$proarr["id"]}">
    <td style="width:9.2%;">
     
        <input name="pro[pro_id][]" value="{$data[0]['pro_id']}" type="hidden">
        <input  value="{$data[0]['name']}" type="text" style="max-width:100px;" class="form-control">
    </td>
    <td style="width:9.2%;">
       
        {$data[0]['sn']}
    </td>
    {$str}
    <td style="width:7.0%;" ><input name="pro[sum][]" type="number" class="form-control sum" readonly value="$sum"></td>
    <td style="width:7.0%;"><input name="pro[avg][]" type="number" class="form-control avg" readonly value="$avg"></td>
</tr>
EOF;
            echo $aaa;
        }else{ //不存在

            $data = Db::table('pro_products')->where('id',$id)->find();

            $str = '';

            foreach($kaoheqi2s as $k=>$v){
                 $str .= "<td style=\"width:5.633%;\"><input name=\"pro[".$v['id']."][]\" type=\"number\" class=\"form-control aa\">".$data['unit']."</td>";
            }
            $aaa = <<<EOF
<tr id="id{$data['id']}">
    <td style="width:9.2%;">
        <input name="pro[pro_id][]" value="{$data['id']}" type="hidden">
        <input  value="{$data['pro_name']}" type="text" style="max-width:100px;" class="form-control">
    </td>
    <td style="width:9.2%;">
       {$data['pro_no']}
    </td>
    {$str}
    <td style="width:7.0%;" ><input name="pro[sum][]" type="number" class="form-control sum" readonly></td>
    <td style="width:7.0%;"><input name="pro[avg][]" type="number" class="form-control avg" readonly></td>
</tr>
EOF;

            echo $aaa;
        }




    }
}
